package com.slw.caiji.ws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.slw.caiji.dto.Message;
import com.slw.caiji.dto.WebSocketData;
import lombok.extern.slf4j.Slf4j;
import nonapi.io.github.classgraph.json.JSONUtils;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/chatRoom/{senderId}")
@Component
@Slf4j
public class WsServeEndPont {


    // 记录当前链接个数
    static ConcurrentHashMap<String, WebSocketData> sessionMap = new ConcurrentHashMap<>();

    //
    private final WebSocketData webSocketData = new WebSocketData();



    // 连接建立时执行的操作
    @OnOpen
    public void OnOpen (Session session, @PathParam("senderId") String senderId, @PathParam("communicationId") String communicationId) {
        webSocketData.setSession(session);
        webSocketData.setCommunicationId(communicationId);
        sessionMap.put(senderId, webSocketData);
        log.info("有新的用户加入，senderId="+senderId + "当前总在线人数为:" + sessionMap.size());
        log.info("websocket is open");
    }



    /**
     *
     * msg添加结构
     * msg:{
     *    type: 消息类型， txt:文本内容   media：媒体文件（前端自己根据后缀名去处理） ping：前端心跳机制（后端单独处理心跳）
     *    value: 消息主体数据
     * }
     * */

    // 收到客户端消息执行的操作
    @OnMessage
    public void onMessage(String msg, @PathParam("senderId") String senderId) throws IOException {
        final WebSocketData webSocketData = sessionMap.get(senderId);
        final Session session = webSocketData.getSession();



        if(session != null) {
            final Message message = JSON.parseObject(msg, Message.class);
            final String type = message.getType();
            if(type.equals("ping")) {
//                回复客户端心跳
                session.getBasicRemote().sendText("{\"type\":\"ping\"}");
            }else{
                sendMessage(webSocketData, msg);
            }
        }
//        return "已收到你的消息";
    }

    private void sendMessage(WebSocketData webSocketData, String message) {
        sessionMap.keySet().forEach(item -> {
            try {
                final String id = webSocketData.getSession().getId();
                final String id1 = sessionMap.get(item).getSession().getId();
                sessionMap.get(item).getSession().getBasicRemote().sendText(message);
            } catch (IOException exception) {
                log.info("sendMessage error");
                exception.printStackTrace();
            }
        });
        if(message != null) {
        }
    }



    // 连接关闭时执行的操作
    @OnClose
    public void OnClose (Session session) {
        sessionMap.remove(session.getId());
        log.info("websocket is close");
    }

    @OnError
    public void OnError(Session session, Throwable throwable) {
        log.info("websocket error");
        sessionMap.remove(session.getId());
        throwable.printStackTrace();
    }

//     定时任务：间隔时间5s
//    @Scheduled(cron = "*/5 * * * * * ")
    public void sendMsg () {
        log.info("当前总在线人数为:" + sessionMap.size());
        sessionMap.keySet().forEach(item->{
            try {
                sessionMap.get(item).getSession().getBasicRemote().sendText("ping");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
